package com.zcm.service.auth.impl;

import org.springframework.social.oauth1.AuthorizedRequestToken;
import org.springframework.social.oauth1.OAuth1Operations;

import com.zcm.config.ApplicationConfig;
import com.zcm.service.auth.AuthorizeService;
import com.zcm.service.support.ConnectionFacoryRegistryUtil;
import com.zcm.service.weibo.serviceprovider.sina.api.model.MyOAuthToken;
import com.zcm.service.weibo.serviceprovider.sina.connect.SinaWeiboConnectionFactory;

/**
 * 进行认证服务的实现类, 底层调用spring social 的认证接口
 * @author Administrator
 *
 */
public class SinaAuthorizeServiceImpl implements AuthorizeService {

	private ApplicationConfig applicationConfig;
	
	public SinaAuthorizeServiceImpl() {
	}

	public AccessToken getAccessToken(RequestToken reqToken) {
		SinaWeiboConnectionFactory swcf = ConnectionFacoryRegistryUtil.getSinaConnectionFactory();
		OAuth1Operations swOauth1 = swcf.getOAuthOperations();
		MyOAuthToken oauthToken = new MyOAuthToken(reqToken.getReqeustToken(), reqToken.getTokenSecret());
		AuthorizedRequestToken authReqToken = new AuthorizedRequestToken(oauthToken, reqToken.getOauthVerifier());
		MyOAuthToken accessOauthToken = (MyOAuthToken)swOauth1.exchangeForAccessToken(authReqToken, null);
		AccessToken accessToken = new AccessToken(accessOauthToken.getValue(), accessOauthToken.getUid(), accessOauthToken.getSecret(), accessOauthToken.getScreenName());		
		return accessToken;
	}
	
	public String getAuthorizationURL(RequestToken reqToken){
		SinaWeiboConnectionFactory swcf = ConnectionFacoryRegistryUtil.getSinaConnectionFactory();
		OAuth1Operations swOauth1 = swcf.getOAuthOperations();
		String authorizationUrl = swOauth1.buildAuthorizeUrl(reqToken.getReqeustToken(), null);
		return authorizationUrl;
	}

	public RequestToken getRequestToken() {
		
		SinaWeiboConnectionFactory swcf = ConnectionFacoryRegistryUtil.getSinaConnectionFactory();
		OAuth1Operations swOauth1 = swcf.getOAuthOperations();
		MyOAuthToken oauth1Token = (MyOAuthToken)swOauth1.fetchRequestToken(this.applicationConfig.getSinaCallbackUrl(), null);
		RequestToken resToken = new RequestToken(oauth1Token.getValue(), oauth1Token.getSecret());
		return resToken;
	}

	public ApplicationConfig getApplicationConfig() {
		return applicationConfig;
	}

	public void setApplicationConfig(ApplicationConfig applicationConfig) {
		this.applicationConfig = applicationConfig;
	}
}
